package com.ljs.springbootinit.manager;

import com.ljs.springbootinit.common.ErrorCode;
import com.ljs.springbootinit.config.RedissonConfig;
import com.ljs.springbootinit.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Redisson限流操作
 */

@Service
public class RedisLimitManage {
    @Resource
    private RedissonConfig redissonConfig;
    public void doLimit(String key){
        RedissonClient redissonClient = redissonConfig.redissonClient();
        // 创建限流器
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);

        // 设置限流器的速率
        boolean result = rateLimiter.trySetRate(RateType.OVERALL, 5, 3, RateIntervalUnit.SECONDS);// 每秒最多 5 次
        if (!result) {
            throw new BusinessException(ErrorCode.TOO_MANY_REQUESTS_ERROR);
        }
    }
}
